package wwy.Service;

import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import wwy.Common.LogicService;
import wwy.Dao.AddressDao;
import wwy.Dto.AddressDto;
import wwy.entity.Address;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressService extends LogicService<AddressDao, Address, Long> {
    private final UserService userService;
    public AddressService(@Autowired AddressDao dao, UserService userService) {
        super(dao); this.userService = userService;}

    @Transactional
    public void delete(Long id) {
        DELETE(id);
    }
    @Transactional
    public void update(AddressDto address) {
        Address oldAddress = GET(address.getId());
        oldAddress.setName(address.getName());
        oldAddress.setAddress(address.getAddress());
        oldAddress.setPhone(address.getPhone());
        oldAddress.setSex(address.getSex());
        dao.save(oldAddress);
    }
    @Transactional
    public void add(AddressDto address) {
        address.setId(null);
        Address newAddress = modelMapper.map(address, Address.class);
        newAddress.setUser(userService.GET(address.getUser_id()));
        dao.save(newAddress);

    }
    @Transactional
    public List<AddressDto> findUserAddressByUser_Id(Long id) {
        List<Address> addresses = dao.findByUser_Id(id);
        List<AddressDto> addressDtoS = new ArrayList<>();
        for (Address address : addresses) {
            addressDtoS.add(modelMapper.map(address, AddressDto.class));
        }
        return addressDtoS;
    }

    //添加默认地址
    @Transactional
    @EventListener(ApplicationReadyEvent.class)
    @Order(3)
    public void addDefaultAddress() {
        if (dao.count() > 0) return;
        Address address = new Address();
        address.setName("习近平先生");
        address.setAddress("沈阳市浑南区智慧四街规划大厦北区34楼34-10-56号");
        address.setPhone("12345678901");
        address.setSex("男");
        address.setUser(userService.GetUserByUserName("user2"));
        dao.save(address);

        Address address1 = new Address();
        address1.setName("特没谱先生");
        address1.setAddress("华盛顿市西城区白宫");
        address1.setPhone("12345678902");
        address1.setSex("男");
        address1.setUser(userService.GetUserByUserName("user2"));
        dao.save(address1);

        Address address2 = new Address();
        address2.setName("梅超风女士");
        address2.setAddress("杭州市西湖区桃花岛");
        address2.setPhone("12345678903");
        address2.setSex("女");
        address2.setUser(userService.GetUserByUserName("user2"));
        dao.save(address2);
    }
}

